package com.kfm.hotel.service.impl;

import com.kfm.hotel.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;

@Service
public class MailServiceImpl implements MailService {

    public static final String SUBJECT = "开发喵酒店登录验证码";
    @Autowired
    private JavaMailSender sender;

    @Autowired
    private Environment environment;


    @Override
    public void sendEmail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(environment.getProperty("spring.mail.username"));
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        sender.send(message);
    }

    @Override
    public int sendLoginCodeEmail(String to) throws MessagingException {
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(environment.getProperty("spring.mail.username"));
        helper.setTo(to);
        helper.setSubject(SUBJECT);
        int code = (int)((Math.random() * 9 + 1) * 100000);
        String htmlContent = "您的账号于" + LocalDateTime.now() + "在" + environment.getProperty("spring.application.name") + "登录"
                + "验证码为：<h3>" + code + "</h3>";
        helper.setText(htmlContent, true); // 第二个参数设置为 true，表示内容为 HTML
        sender.send(message);
        return code;
    }
}
